﻿using MySqlConnector;

namespace Front._1127;

public partial class Login : Form
{
    public Login()
    {
        InitializeComponent();
    }

    private void Login_Load(object sender, EventArgs e)
    {
        // 界面设置已在Designer中完成，这里保留为空
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            // 验证输入是否为空
            string account = textBox1.Text?.Trim();
            string password = textBox2.Text;
            
            if (string.IsNullOrEmpty(account))
            {
                MessageBox.Show("请输入账号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBox1.Focus();
                return;
            }
            
            if (string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBox2.Focus();
                return;
            }

            // 确保密码不为null再进行加密
            string pwd = MD5Helper.GetMD5(password);
            
            // 构建连接字符串
            string connectionString = "server=localhost;port=3306;database=book;user=root;password=123456;charset=utf8mb4;AllowPublicKeyRetrieval=True;";
            
            using var connection = new MySqlConnection(connectionString);
            connection.Open();
            
            // 使用参数化查询
            string sql = "SELECT * FROM admin_info WHERE admin_account = @account AND admin_password = @pwd";
            using var command = new MySqlCommand(sql, connection);
            
            // 使用AddWithValue方法添加参数，MySqlConnector会正确处理类型
            command.Parameters.AddWithValue("@account", account);
            command.Parameters.AddWithValue("@pwd", pwd);
            
            using var reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                //登录成功，跳转主窗体
                MainForm mainForm = new MainForm();
                mainForm.Show();
                this.Hide();//隐藏登录窗体
                
                // 设置主窗体关闭时退出应用程序
                mainForm.FormClosed += (s, args) => this.Close();
            }
            else
            {
                //登录失败
                MessageBox.Show("账号或密码错误，请重新输入！", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.textBox2.Text = "";
                this.textBox2.Focus();//将焦点设置到密码输入框
            }
        }
        catch (MySqlException ex)
        {
            // 处理数据库异常
            MessageBox.Show($"数据库错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            // 处理其他异常
            MessageBox.Show($"登录失败：{ex.Message}\n错误类型：{ex.GetType().Name}\n堆栈跟踪：{ex.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}